package org.elanfox.cloud.common.web.interceptor;

import com.alibaba.fastjson.JSON;
import org.elanfox.cloud.common.annotation.IgnoreToken;
import org.elanfox.cloud.common.base.ApiResult;
import org.elanfox.cloud.common.enums.CommonCode;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;

/**
 * @author allan
 * @date 2019-08-16
 */
public class RestAuthInterceptor implements HandlerInterceptor {
    private final byte[] SECRET = "skldjfl12k!@$$#2..".getBytes();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        IgnoreToken authorized = handlerMethod.getBeanType().getAnnotation(IgnoreToken.class);
        if (authorized == null) {
            authorized = handlerMethod.getMethodAnnotation(IgnoreToken.class);
        }
        if (authorized != null) {
            return true;
        }

        String token = request.getHeader("Access-Token");
        response.setCharacterEncoding(StandardCharsets.UTF_8.displayName());
        if (StringUtils.isEmpty(token)) {
            response.setContentType("application/json; charset=utf-8");
            response.getWriter().write(JSON.toJSONString(ApiResult.error(CommonCode.TOKEN_VERIFY_FAILED)));
            return false;
        }

//        JWSObject jwsObject = JWSObject.parse(token);
//
//        JWSVerifier jwsVerifier = new MACVerifier(SECRET);
//
//        if (jwsObject.verify(jwsVerifier)) {
//            return true;
//        }
//
//        response.getWriter().write(JSON.toJSONString(ApiResult.error(CommonCode.TOKEN_VERIFY_FAILED)));
//        return false;
        return true;
    }
}
